<template>
    <lay-card>
      <lay-container>
        <vxe-modal
            v-model="visible"
            :title="editFlag ? '新增策略&保存' : '编辑策略&保存'"
            width="800"
            min-width="600"
            min-height="400"
            resize
            destroy-on-close
        >
          <template #default>
              <PushParams
                  :row-params="rowParams1"
                  @cancel="closeFilterLayer"
              ></PushParams>
          </template>
        </vxe-modal>
        <lay-row space="20">
          <lay-col style="margin-top: 20px">
            <lay-form :model="queryForm" :pane="true">
              <lay-row space="10">
                <lay-col :md="mode === 'page'?6:12">
                  <lay-form-item label="场景" mode="inline" >
                    <lay-input v-model="queryForm.sceneName" style="width: 100%"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="mode === 'page'?6:12">
                  <lay-form-item label="市场" mode="inline" >
                    <lay-select v-model="queryForm.market" >
                      <lay-select-option :value="item.value" :label="item.value" v-for="item in markets"></lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
                <lay-col :md="mode === 'page'?6:0" v-if="mode === 'page'">
                  <lay-form-item label="协议" mode="inline" >
                    <lay-select v-model="queryForm.protocol" >
                      <lay-select-option :value="item.value" :label="item.value" v-for="item in protocols"></lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row space="10">
                <lay-col :md="mode === 'select'? 12:0" v-if="mode === 'select'">
                  <lay-form-item label="协议" mode="inline" >
                    <lay-select v-model="queryForm.protocol" >
                      <lay-select-option :value="item.value" :label="item.value" v-for="item in protocols"></lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
                <lay-col md="12">
                  <lay-button type="normal" @click="queryBatFiles" >查询</lay-button>
                  <lay-button @click="resetFrom" >重置</lay-button>
                  <lay-button type="normal"  @click="setParams(null)" v-if="mode === 'page'">新增</lay-button>
                </lay-col>
              </lay-row>
            </lay-form>
          </lay-col>
        </lay-row>
        <lay-row space="20">
          <lay-col md="24">
            <lay-table
              :page="page"
              :height="heightTable"
              style="min-height: 60%"
              :columns="columns"
              :loading="loading"
              :data-source="dataSource"
              v-model:selectedKeys="selectedKeys"
              @change="change"
            >
            <template v-slot:toolbar>
              <h3>推送策略记录表</h3>
            </template>
            <template v-slot:operator="{ row }">
              <p v-if="mode === 'page'">
                <lay-button type="normal" size="xs" @click="setParams(row)">更新</lay-button>
                <lay-button size="xs" type="danger" @click="deleteRow(row.rowId)">删除</lay-button>
              </p>
              <p v-else>
                <lay-button size="xs" type="normal" @click="selectRow(row.rowId)">选定</lay-button>
              </p>
            </template>
          </lay-table>
          </lay-col>
        </lay-row>
      </lay-container>
    </lay-card>
</template>

<script lang="ts">
export default {
  name: "Strategy"
}
</script>

<script lang="ts" setup>

import {onMounted, reactive, ref} from "vue";
import {notify} from "../../../untils/tip";
import {countStrategy, deleteStrategy, queryStrategy} from "../../../api/market/market";
import {getConfig} from "../../../api/market/basic";
import {layer} from "@layui/layui-vue";
import PushParams from "../../../components/Market/PushParams.vue";

// 定义参数
const {mode, setRowId} = defineProps({
  mode: {type: String, default: 'page'},
  setRowId: {type: Function},
  cancelLay: {type: Function}
});

const emitMethod = defineEmits(["selectRow"]);

const loading = ref(false);
const selectedKeys = ref([]);
const visible = ref(false);
const rowParams1 = ref();
const editFlag = ref(true);
const formSize = ref('sm');
const heightTable = ref('500px');

// 列  列宽135%
const columns: any = ref([]);
const columnsFirst = ref([
    { title:"编号", width: "5%", key:"rowId", sort: "desc" },
    { title:"场景名称", width: "15%", key:"sceneName"},
    // { title:"TCP地址", width: "15%", key:"targetClient"},
    { title:"市场", width: "8%", key:"market" },
    { title:"行情源", width: "8%", key:"protocol" },
    { title:"起始时间", width: "12%", key:"beginTime", sort: "desc" },
    { title:"结束时间", width: "12%", key:"endTime", sort: "desc" },
    // { title:"消息类型", width: "15%", key:"msgType" },
    // { title:"证券代码", width: "10%", key:"securityId" },
    // { title:"证券类别", width: "10%", key:"mdStreamId" },
    // { title:"定时", width: "5%", key:"cornJob" },
    // { title:"触发时间", width: "10%", key:"cornTime" },
    // { title:"推送模式", width: "10%", key:"pushMode" },
    // { title:"推送频率", width: "10%", key:"pushFrequency" },
    // { title:"积压数量", width: "10%", key:"pushCondition" },
    // { title:"模拟日期", width: "10%", key:"mockDate" },
    { title:"备注", width: "16%", key:"description" },
    { title:"更新时间", width: "12%", key:"updateTime" },
    { title:"操作", width: "12%", customSlot:"operator", key:"operator", fixed: "right" }
]);

const columnsTwo = ref([
    { title:"编号", width: "5%", key:"rowId", sort: "desc" },
    { title:"场景名称", width: "40%", key:"sceneName"},
    { title:"市场", width: "20%", key:"market" },
    { title:"协议", width: "20%", key:"protocol" },
    { title:"操作", width: "15%", customSlot:"operator", key:"operator", fixed: "right" }
]);

const dataSource = ref([]);

// 页面加载前查询数据
onMounted(()=>{
  initSet();
  queryBatFiles();
  getSelectItems('market');
  getSelectItems('protocol');
});

const initSet = () => {
  if(mode === 'select'){
    formSize.value = 'xs';
    columns.value = columnsTwo.value;
    heightTable.value = '300px';
  }else {
    columns.value = columnsFirst.value;
    formSize.value = 'sm';
    heightTable.value = '500px';
  }
};

// 下拉框选择的值
const industries: any = ref([]);
const markets: any = ref([]);
const protocols: any = ref([]);

const page = reactive({ current: 1, limit: 10, total: 10 });

const queryForm: any = reactive({
    sceneName: null,
    targetClient: null,
    market: null,
    protocol: null,
    pageNo: 0,
    pageSize: page.limit
});

// 设置参数
const setParams = (data: any) => {
  if(data){
    rowParams1.value = data;
    editFlag.value = false;
  }else {
    rowParams1.value = null;
    editFlag.value = true;
  }
  visible.value = !visible.value;
  console.log("visible:", visible.value, "data: ", rowParams1.value)
};

const queryBatFiles = () => {
  page.current = 1;
  queryFilesCount();
}

const change = () => {
  loading.value = true;
  setTimeout(() => {
    loadDataSource();
    loading.value = false;
  }, 1000);
};

const resetFrom = () => {
  queryForm.sceneName = null;
  queryForm.targetClient = null;
  queryForm.protocol = null;
  queryForm.pageNo = 0;
  queryForm.pageSize = page.limit;
};

const queryFilesCount = async () => {
  let {data, code, message} = await countStrategy(queryForm)
  if(code === 200){
    page.total = data;
    await loadDataSource();
  }else {
    notify('fail', message);
  }
};

const loadDataSource = async () => {
  dataSource.value = [];
  queryForm.pageNo = (page.current - 1)*page.limit;
  queryForm.pageSize = page.limit;
  let {code, data, message} = await queryStrategy(queryForm)
  if(code === 200){
    if(data){
      data.forEach((unit: any)=>{
      unit.id = unit.rowId;
    });
    dataSource.value = data;
    }
  }else {
    notify('fail', message);
  }
};

// 删除数据并刷新页面
const deleteRow = (rowId: number) => {
  layer.confirm("你确认要删除此行数据么？行号是："+rowId,
  {
    btn: [
      {text:'确认', callback: (id: any) => {
        deleteRowApi(rowId);
        layer.close(id); }
      },
      {text:'取消', callback: (id: any) => {
          layer.close(id); }
      }
      ]
    }
  );
};

const deleteRowApi = async (rowId: number) => {
  const queryParams = reactive({row: rowId});
  let {code, data, message} = await deleteStrategy(queryParams);
  if(code === 200){
    notify('success', message);
    await loadDataSource();
  }else {
    notify('fail', message);
  }
};

const closeFilterLayer = () => {
  visible.value = false;
  queryBatFiles();
}

// 获取下拉列表选择的值
const getSelectItems = async (target: string) => {
  let {data, code, message} = await getConfig({target: target})
  if(code === 200){
    switch (target) {
      case 'market': markets.value = data; break;
      case 'industry': industries.value = data; break;
      case 'protocol': protocols.value = data; break;
    }
  }else {
    notify('fail', message);
  }
};

// 关联策略
const selectRow = (rowId: any) => {
  emitMethod("selectRow", rowId)
};

</script>

<style scoped>

</style>